package imoney.server;

import imoney.server.util.IDsManager;
import imoney.server.util.PersistenceManagerFacto;
import imoney.shared.Statics;
import imoney.shared.model.Person;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class ContextListener implements ServletContextListener {

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		/*
		 * TODO : consider the fact of storing the list of logged-in users.
		 * but it might be a bad idea as the servlet container is destroyed
		 * it could be better to start a brand new list.
		 */
	}

	@SuppressWarnings("unchecked")
	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		PersistenceManagerFactory pmf = PersistenceManagerFacto.getPMF();
		PersistenceManager pm = pmf.getPersistenceManager();
		
		String query = "select from "+IDsManager.class.getName();
		List<IDsManager> list = (List<IDsManager>) pm.newQuery(query).execute();
		if(list.isEmpty()){
			IDsManager manager =  new IDsManager();
			pm.makePersistent(manager);
		}
		pm.close();
		
		ArrayList<Person> personList = new ArrayList<Person>();
		ServletContext context = arg0.getServletContext();
		context.setAttribute(Statics.Context_LIST_PERSONS, personList);	
	}

}
